<%--
  Created by IntelliJ IDEA.
  User: YCC
  Date: 2021/12/19
  Time: 16:45
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Include layui CSS -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/layui/2.6.8/css/layui.min.css">

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>camera</title>
    <style>
        #camera {
            float: left;
            margin: 20px;
        }

        #contentHolder {
            width: 300px;
            height: 300px;
            margin-bottom: 10px;
        }

        #btn_snap,#btn_snap1 {
            margin: 0 auto;
            border: 1px solid #f0f0f0;
            background: #5CACEE;
            color: #FFF;
            width: 100px;
            height: 36px;
            line-height: 36px;
            border-radius: 8px;
            text-align: center;
            cursor: pointer;
            cursor: pointer;
            /*禁止选择*/
            -webkit-touch-callout: none;
            /* iOS Safari */
            -webkit-user-select: none;
            /* Chrome/Safari/Opera */
            -khtml-user-select: none;
            /* Konqueror */
            -moz-user-select: none;
            /* Firefox */
            -ms-user-select: none;
            /* Internet Explorer/Edge */
            user-select: none;
            /* Non-prefixed version, currently not supported by any browser */

        }

        #imgBoxxx {
            width: 200px;
            margin: 60px 20px 20px;
            /* border-radius: 50%; */
        }
    </style>
</head>

<body >
<h3>正在识别中...请稍后</h3>
<div id="camera">
    <div id="contentHolder">
        <video id="video" style="width: 1450px;height: 900px;" width="300" height="300"  onclick="myfunction()" autoplay></video>
        <canvas style="display:none;" id="canvas" width="300" height="300"   onclick="myfunction()"></canvas>
    </div>

</div>

<script>

    var canvas = document.getElementById("canvas"),
        pzBtn = document.getElementById("btn_snap"),
        context = canvas.getContext("2d"),
        video = document.getElementById("video");

    // alert('该页面会调用您的摄像头')

    // 旧版本浏览器可能根本不支持mediaDevices，我们首先设置一个空对象
    if (navigator.mediaDevices === undefined) {
        navigator.mediaDevices = {};
    }

    // 一些浏览器实现了部分mediaDevices，我们不能只分配一个对象
    // 使用getUserMedia，因为它会覆盖现有的属性。
    // 这里，如果缺少getUserMedia属性，就添加它。
    if (navigator.mediaDevices.getUserMedia === undefined) {
        navigator.mediaDevices.getUserMedia = function (constraints) {
            // 首先获取现存的getUserMedia(如果存在)
            var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
            // 有些浏览器不支持，会返回错误信息
            // 保持接口一致
            if (!getUserMedia) {
                return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
            }
            //否则，使用Promise将调用包装到旧的navigator.getUserMedia
            return new Promise(function (resolve, reject) {
                getUserMedia.call(navigator, constraints, resolve, reject);
            });
        }
    }
    var constraints = {

        audio: false,
        video: {
            height: 300
        }
    }
    navigator.mediaDevices.getUserMedia(constraints)
        .then(function (stream) {
            var video = document.querySelector('video');
            // 旧的浏览器可能没有srcObject
            if ("srcObject" in video) {
                video.srcObject = stream;
            } else {
                //避免在新的浏览器中使用它，因为它正在被弃用。
                video.src = window.URL.createObjectURL(stream);
            }
            video.onloadedmetadata = function (e) {
                video.play();
            };
        })
        .catch(function (err) {
            console.log(err.name + ": " + err.message);
        });
    var abc ;

    function myfunction() {

        // 点击，canvas画图
        context.drawImage(video, 0, 0, 300, 300);
        // 获取图片base64链接
        var image = canvas.toDataURL('image/png');
        /*console.log(image);*/
        // 定义一个img
        var img = new Image();
        var abc1=image.split(",");
        abc=abc1[1]

        //设置属性和src
        img.id = "imgBox";
        img.src = image;
/*
        //将图片添加到页面中
        document.body.appendChild(img);*/


        // base64转文件
        function dataURLtoFile(dataurl, filename) {
            var arr = dataurl.split(','),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new File([u8arr], filename, {
                type: mime
            });
        }
        sendImage()

    };


    function sendImage() {
        var userId=$("input[name='userId']").val()
        /*var dataURLtoFile1 = dataURLtoFile(image, date);*/
        var  data={image1:abc}
        $.ajax({
            "url": "${pageContext.request.contextPath}/staff/sendController",
            "type": "post",
            "data":  JSON.stringify(data),
            "dataType": "json",
            "contentType":"application/json;charset=utf-8",
            "success": function(result) {
                if(result.code==200){
                    alert(result.msg)
                }else if(result.code==300){
                    alert(result.msg)
                }else if(result.code==400) {
                    alert(result.msg)
                }else{
                    alert("ok")
                }
            },
            "error": function() {
                alert("没有找到您！")
            }
        });
    }

</script>
<script>
    function checkTimeAndCallFunction() {
        // 获取当前时间
        var currentTime = new Date();

        // 获取当前小时
        var currentHour = currentTime.getHours();

        // 判断是否晚上10点
        if (currentHour === 22) {
            // 调用需要执行的函数
            yourFunction();
        } else {
            // 计算距离晚上10点的剩余时间
            var remainingTime = (22 - currentHour) * 60 * 60 * 1000; // 转换为毫秒

            // 设置定时器，在剩余时间到达后调用函数
            setTimeout(yourFunction, remainingTime);
        }
    }
    // 要执行的函数
    function yourFunction() {
        $.ajax({
            "url": "${pageContext.request.contextPath}/staff/addStaffPunchCardTwoController",
            "type": "post",
            "data":  {},
            "dataType": "json",
            "contentType":"application/json;charset=utf-8",
            "success": function(result) {
                if(result.code==200){
                    alert(result.msg)
                }else if(result.code==300){
                    alert(result.msg)
                }else if(result.code==400) {
                    alert(result.msg)
                }else{
                    alert("出错啦！")
                }
            },
            "error": function() {
                alert("没有找到您！")
            }
        });
    }
    // 调用函数进行时间检查
    checkTimeAndCallFunction();
</script>

</body>

</html>
